package api

import (
	"blog/app/common"
	fileRequeset "blog/app/request/file"
	"blog/core/request"
	"blog/utils/upload"

	"github.com/gin-gonic/gin"
)

type File struct {
}

type FileResp struct {
	Url string `json:"url"`
}

func (f File) GetFileConfig(req request.InterfaceRequest) {

	req.Response().Data(ServiceGroup.file.GetFileConfig()).Success()
}

// 附件列表
func GetLists(req request.InterfaceRequest) {
	param := fileRequeset.FileLists{
		Page:  req.GetIntDefault("page", 1),
		Limit: req.GetIntDefault("limit", 10),
	}
	lists, count := ServiceGroup.file.GetLists(param)
	req.Response().Data(lists).Count(count).Success()
}

// Upload 文件上传
func Upload(c *gin.Context) {
	req := request.Request(c)
	fileOrigin, err := c.FormFile("file")
	if err != nil {
		req.Response().Message("没有上传文件").Error()
		return
	}

	render, _ := fileOrigin.Open()
	file := upload.NewFile(fileOrigin.Filename, fileOrigin.Size, render, upload.Set.SetTitle(fileOrigin.Filename), upload.Set.SetMineType(fileOrigin.Header.Get("Content-Type")))
	defer render.Close()
	hash := file.GetMd5Hash()
	if url := common.Cache.File(hash); url != "" {
		req.Response().Data(FileResp{
			Url: url,
		}).Message("上传成功").Success()
		return
	}

	create, err := ServiceGroup.file.Upload(file, true)

	if err != nil {
		req.Response().Message(err.Error()).Error()
		return
	}

	url := "http://"
	if create.IsHttps == 1 {
		url = "https://"
	}

	url = url + create.Domain + "/" + create.Url
	common.Cache.FileSet(hash, url)
	req.Response().Data(FileResp{
		Url: url,
	}).Message("上传成功").Success()
}
